package com.libui.webview.jsinterface.handlers

import com.libbase.cast
import com.libui.thirdpartsdk.SDKManager
import com.libui.thirdpartsdk.share.ShareCompletion
import com.libui.webview.WebViewEx
import com.libui.webview.jsinterface.WebViewHandlerInterface

class ShareHandler : WebViewHandlerInterface {
    companion object {
        const val id: String = "share"
    }

    override val id: String
        get() {
            return ShareHandler.id
        }

    override fun handle(webView: WebViewEx?, params: Map<String, Any>?) {
        if (webView == null) {
            return
        }

        if (params == null) {
            return
        }

        val uuid: String = params["uuid"] as? String ?: return

        val shareObject = cast<Map<String, Any>>(params["shareObject"])
        if (shareObject == null) {
            runFailCallback(webView, uuid, 1, "share:fail, no share object", null, params)
            return
        }

        val shareCompletion: ShareCompletion = { success ->
            if (success) {
                runSuccessCallback(webView, uuid, 0, "share:ok", null, params)
            } else {
                runFailCallback(webView, uuid, 1, "share:fail", null, params)
            }
        }

        val shareType = params["shareType"] as? String
        if (shareType != null) {
            SDKManager.instance.share(shareType, shareObject, shareCompletion)
        } else {
            SDKManager.instance.share(shareObject, shareCompletion)
        }
    }
}